package cn.lix.sc.rpc.commons.spring;

import cn.lix.sc.rpc.commons.annotations.EnableOptions;
import cn.lix.sc.rpc.commons.interfaces.Options;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 初始化枚举选项类
 * @Author 木林森
 * @Date 2021/6/9
 */
@Configuration
public class LoadEnumOptions implements CommandLineRunner, ImportAware {

    private String[] locationPatterns;

    private static final Map<String, Options[]> map = new HashMap<>(32);

    @Override
    public void run(String... args) throws Exception {
        PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        for (String pattern : locationPatterns) {
            String path = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(pattern) + "/**/*.class";
            Resource[] resources = resourcePatternResolver.getResources(path);
            MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                MetadataReader reader = metadataReaderFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(className);
                if (Enum.class.isAssignableFrom(clazz) && Options.class.isAssignableFrom(clazz)) {
                    Options[] constants = (Options[]) clazz.getEnumConstants();
                    map.put(clazz.getSimpleName(), constants);
                }
            }
        }
    }


    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        Map<String, Object> defaultAttrs = importMetadata.getAnnotationAttributes(EnableOptions.class.getName(), true);
        this.locationPatterns = (String[]) defaultAttrs.get("value");
    }

    /**
     * 根据枚举类名获取枚举选项列表
     * @param key
     * @return
     */
    public static List<Map<String, Object>> getEnumOptions(String key) {
        Options[] options = map.get(key);
        if(options == null || options.length < 1){
            return Collections.emptyList();
        }
        return Arrays.stream(options)
                .filter(e -> !e.isIgnore())
                .sorted(Comparator.comparing(Options::getSort))
                .map(e -> {
                    Map<String, Object> m = new HashMap<>(4);
                    m.put("value", e.getValue());
                    m.put("label", e.getLabel());
                    return m;
                }).collect(Collectors.toList());
    }
}
